package codingforgreat.lchot150;

public class Lc289 {
    public void gameOfLife(int[][] board) {
        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[0].length;j++){
                int neighbors = neighbor(board,i,j);
                if(neighbors == 3 ||  (board[i][j] == 1 && neighbors == 2)){
                    board[i][j] |= 2;
                }
            }
        }
        for(int i = 0;i < board.length;i++){
            for(int j = 0;j < board[0].length;j++){
                board[i][j] >>= 1;
            }}
    }
    public int neighbor(int[][] board,int i,int j){
        return f(board,i + 1,j) + f(board,i - 1,j) + f(board,i,j + 1) + f(board,i,j - 1) + f(board,i - 1,j - 1) + f(board,i - 1,j + 1) + f(board,i + 1,j - 1) + f(board,i + 1,j + 1);
    }
    // b[i][j] 上面有1，就返回1，上面不是1，就返回0
    public static int f(int[][] b, int i, int j) {
        return (i >= 0 && i < b.length && j >= 0 && j < b[0].length && (b[i][j] & 1) == 1) ? 1 : 0;
    }
}
